<template>
    <div class='fxn-body'>
        <div class="fxn-top">
            <el-button type="danger" icon="Plus" @click="handleOp(1)">添加</el-button>
        </div>
        <!-- Top End -->
        <div class="fxn-section wrap-fixed fxn-margin-t-20">
            <el-table v-loading="loading" border :data="listData">
                <el-table-column label="ID" prop="id" width="80" />
                <el-table-column label="企业名称" prop="name">
                    <template #default="scope">
                        <el-link type="danger" :underline="false" @click="handlePath(scope.row)">{{scope.row.name}}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="企业简称" prop="short_name" />
                <el-table-column label="联系人" prop="contacts_name" />
                <el-table-column label="手机号码" prop="contacts_phone" />
                <el-table-column label="状态" prop="status" width="80">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" @change="handleStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-link type="danger" :underline="false" @click="handleAuth(scope.row)">授权</el-link>
                        <el-link type="danger" :underline="false" @click="handleOp(2,scope.row)">编辑</el-link>
                        <el-link type="danger" :underline="false" @click="handleDel(scope.row)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- Section End -->
        <div class="fxn-page fixed">
            <el-pagination v-model:current-page="page" v-model:page-size="perPage" :page-sizes="[10, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next" :total="count" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- Page End -->

        <!-- 操作团队 -->
        <el-dialog v-model="opDialog" :title="opTitle" width="700" :before-close="handleClose">
            <el-form :model="opForm" ref="opRef" :rules="opRules" label-width="100">
                <el-form-item label="企业名称" prop="name">
                    <el-input v-model="opForm.name" placeholder="请输入企业名称"></el-input>
                </el-form-item>
                <el-form-item label="企业简称" prop="short_name">
                    <el-input v-model="opForm.short_name" placeholder="请输入企业简称"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="contacts_name">
                    <el-input v-model="opForm.contacts_name" placeholder="请输入联系人"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="contacts_phone">
                    <el-input v-model="opForm.contacts_phone" placeholder="请输入联系人手机号码"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="danger" :loading="btnLoading" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
        <!-- 操作团队 End -->

        <!-- 授权 -->
        <el-dialog v-model="authDialog" title="授权" :before-close="handleAuthClose">
            <div class="fxn-info fxn-margin-b-20">
                <p>本授权规则严格的遵循父子互相关联的做法，请严格遵守相关的要求进行授权管理：</p>
                <p>案例A：如需授权《系统管理--权限管理》菜单进行访问列表数据，其它功能操作节点不授权。勾选的菜单如下：</p>
                <p class="fxn-text-indent">系统管理-->权限管理</p>
                <p>案例B：如需授权《系统管理--权限管理--添加、系统管理--权限管理--编辑》的菜单进行功能操作权限。勾选的菜单及功能节点如下：</p>
                <p class="fxn-text-indent">系统管理-->权限管理-->添加、系统管理-->权限管理-->编辑</p>
                <p class="fxn-text-red fxn-text-indent">如不严格遵守以上相关的规则，导致系统左侧菜单或系统错误，则系统无法使用。请操作人员严谨按规范操作！</p>
            </div>
            <!-- Info End -->
            <el-tree class="is-penultimate" ref="tree" :data="menuArr" node-key="id" default-expand-all show-checkbox accordion :default-expanded-keys="[1]" :expand-on-click-node="true" :check-strictly="true" :default-checked-keys="arrayData" :props="defaultProps">
                <template #default="{data}">
                    <span>{{data.title}}</span>
                </template>
            </el-tree>
            <template #footer>
                <el-button type="danger" plain @click="handleCheck">{{checkTitle}}</el-button>
                <el-button @click="handleAuthClose">取消</el-button>
                <el-button type="danger" :loading="btnLoading" @click="handleAuthSubmit">确认</el-button>
            </template>
        </el-dialog>
        <!-- 授权 End -->
    </div>
</template>

<script>
    import { defineComponent, reactive, getCurrentInstance, onMounted, toRefs, computed } from 'vue'
    import { useRouter } from 'vue-router'
    import { useStore } from 'vuex'
    export default defineComponent({
        name: '',
        setup() {
            const { proxy } = getCurrentInstance();
            const router = useRouter();
            const store = useStore();

            //初始化数据
            const state = reactive({
                count: 0,
                page: 1,
                perPage: 10,
                loading: false,
                listData: [],

                //操作
                btnLoading: false,
                opDialog: false,
                opTitle: '',
                opRef: '',
                opForm: {
                    select: '',
                    name: '',
                    short_name: '',
                    contacts_name: '',
                    contacts_phone: '',
                },
                opRules: {
                    name: [
                        { required: true, message: '请输入企业名称', trigger: 'blur' },
                    ],
                    short_name: [
                        { required: true, message: '请输入企业简称', trigger: 'blur' },
                    ],
                    contacts_name: [
                        { required: true, message: '请输入联系人', trigger: 'blur' },
                    ],
                    contacts_phone: [
                        { required: true, message: '请输入联系人手机号码', trigger: 'blur' },
                    ],
                },

                //授权
                checkTitle: '全选',
                authDialog: false,
                isChecked: false,
                rowID: '',
                menuArr: [],
                arrayData: [],
                defaultProps: {
                    value: 'id',
                    label: 'title',
                    children: 'children',
                    class: "customNodeClass",
                },
            })

            //列表
            const getList = (page,perPage) => {
                state.loading = true;
                proxy.$http.get('/sys/Company/index',{
                    page: page ? page : 1,
                    perPage: perPage ? perPage : 10,
                })
                .then(res=> {
                    state.loading = false;
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        state.count = data.count;
                        state.page = data.page;
                        state.perPage = data.perPage;
                        state.listData = data.list;
                    }
                })
            }

            //操作团队
            const handleOp = (type,row) => {
                if(type == 1){
                    state.opForm.id = '';
                    state.opTitle = '添加';
                }else{
                    state.opTitle = '编辑';
                    proxy.$http.get('/sys/Company/op',{id: row.id})
                    .then(res=> {
                        const { code, msg ,data } = res;
                        if(code != 1){
                            return proxy.$msg.error(msg);
                        }else{
                            state.opForm = data;
                        }
                    })
                }
                state.opDialog = true;
            }

            //提交团队
            const handleSubmit  = () => {
                state.opRef.validate((valid) => {
                    if(valid){
                        proxy.$http.post('/sys/Company/op',state.opForm)
                        .then(res=> {
                            const { code, msg ,data } = res;
                            if(code != 1){
                                return proxy.$msg.error(msg);
                            }else{
                                state.opDialog = false;
                                proxy.$refs.opRef.resetFields();
                                proxy.$msg.success('提交成功!');
                                getList(state.page,state.perPage);
                            }
                        })
                    }
                })
            }

            //关闭操作
            const handleClose = () => {
                state.opDialog = false;
                proxy.$refs.opRef.resetFields();
            }

            //全选
            const handleCheck = () => {
                state.isChecked = !state.isChecked;
                if(state.isChecked){
                    //全选
                    state.checkTitle = '取消全选';
                    proxy.$refs.tree.setCheckedKeys(getAllKey(state.menuArr));
                }else{
                    //取消全选
                    state.checkTitle = '全选';
                    proxy.$refs.tree.setCheckedKeys([]);
                }
            }

            //全选数据
            const getAllKey = (nodes) => {
                let keys = [];
                nodes.forEach(node => {
                    keys.push(node.id);
                    if (node.children && node.children.length) {
                        keys = keys.concat(getAllKey(node.children));
                    }
                });
                return keys;
            }

            //授权
            const handleAuth = (row) => {
                state.authDialog = true;
                state.isChecked = false;
                state.rowID = row.id;
                proxy.$http.get('/sys/Company/menuAuth',{id: row.id})
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        if(data.company_nodes){
                            state.arrayData = (data.company_nodes).split(',');
                        }
                        state.menuArr = data.menus_tree;
                    }
                })
            }

            //提交授权
            const handleAuthSubmit = () => {
                let checkKey = proxy.$refs.tree.getCheckedKeys();
                let HalfCheckKey = proxy.$refs.tree.getHalfCheckedKeys();
                let nodes = checkKey.concat(HalfCheckKey);
                nodes = [...new Set(nodes)];

                proxy.$http.post('/sys/Company/menuAuth',{
                    id: state.rowID,
                    nodes: String(nodes),
                })
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        state.authDialog = false;
                        proxy.$msg.success('提交成功!');
                        getList(state.page,state.perPage);
                    }
                })
            }

            //关闭授权操作
            const handleAuthClose = () => {
                state.authDialog = false;
                state.arrayData = [];
            }

            //修改状态
            const handleStatus = (row) => {
                proxy.$http.post('/sys/Company/state',{id: row.id, status:row.status})
                .then(res=>{
                    const { code, msg , data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        proxy.$msg.success('修改成功!');
                        getList(state.page,state.perPage);
                    }
                })
            }

            //删除
            const handleDel = (row) => {
                proxy.$confirm("此操作将会删除该数据, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(async () => {
                    proxy.$http.post('/sys/Company/remove',{id: row.id})
                    .then(res=> {
                        let { code, msg, data } = res;
                        if(code != 1){
                            return proxy.$msg.error(msg);
                        }else{
                            proxy.$msg.success('删除成功!');
                            getList(state.page,state.perPage);
                        }
                    })
                })
                .catch(() => {})
            }

            //跳转企业用户
            const handlePath = (row) => {
                router.push({path: '/TeamUser', query: {id: row.id, name: row.name}});
            }

            //分页
            const handleSizeChange = (val) => {
                state.perPage = val;
                getList(state.page,state.perPage);
            }

            //页码
            const handleCurrentChange = (val) => {
                state.page = val;
                getList(state.page,state.perPage);
            }
            
            //Dom加载
            onMounted(()=>{
                getList();
            })
            
            return {
                ...toRefs(state),
                
                //请求方法
                getList,
                getAllKey,
                handleOp,
                handleSubmit,
                handleClose,
                handleCheck,
                handleAuth,
                handleAuthSubmit,
                handleAuthClose,
                handleStatus,
                handleDel,
                handlePath,
                
                //组件方法
                handleSizeChange,
                handleCurrentChange,
            }

        },
    })
</script>

<style scoped>
    
</style>